/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.templet.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentType;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.publish.entity.EleSourceGroupPublish;
import com.thinkgem.jeesite.modules.publish.entity.EleTempletPublish;
import com.thinkgem.jeesite.modules.publish.service.EleTempletPublishService;
import com.thinkgem.jeesite.modules.source.entity.background.EleSourceBackground;
import com.thinkgem.jeesite.modules.source.entity.font.EleSourceFont;
import com.thinkgem.jeesite.modules.source.service.font.EleSourceFontService;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.entity.EleTempletSource;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 模板管理Controller
 * @author ZC
 * @version 2017-04-27
 */
@Controller
@RequestMapping(value = "${adminPath}/templet/eleTemplet")
public class EleTempletController extends BaseController {

    @Autowired
	private EleTempletService eleTempletService;
    @Autowired
    private EleEquipmentService eleEquipmentService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private EleTempletPublishService eleTempletPublishService;
    @Autowired
	private SystemService systemService;
	@Autowired
	private EleSourceFontService eleSourceFontService;
	
	@ModelAttribute
	public EleTemplet get(@RequestParam(required=false) String id) {
		EleTemplet entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eleTempletService.get(id);
		}
		if (entity == null){
			entity = new EleTemplet();
		}
		return entity;
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = {"list", ""})
	public String list(EleTemplet eleTemplet, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EleTemplet> page = eleTempletService.findPage(new Page<EleTemplet>(request, response), eleTemplet); 
		model.addAttribute("page", page);
		return "modules/templet/eleTempletList";
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = "form")
	public String form(EleTemplet eleTemplet, Model model) {
		model.addAttribute("eleTemplet", eleTemplet);
        model.addAttribute("eleTempletSource", new EleTempletSource());
		return "modules/templet/eleTempletForm";
	}

    @RequiresPermissions("templet:eleTemplet:edit")
    @RequestMapping(value = "save")
    public String save(EleTemplet eleTemplet, Model model,HttpServletRequest request) {

        if (!beanValidator(model, eleTemplet)){
            return form(eleTemplet, model);
        }
        System.out.println(eleTemplet.getBackground()+"****************************************");
        eleTempletService.save(eleTemplet,null);

		
        // 生成代码
        /*if("0".equals(eleTemplet.getFlag())){
            return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/form?id="+eleTemplet.getId();
        }
        else{*/
            return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/show?id="+eleTemplet.getId();
        /*}*/
    }
    public void createTemplateFile(EleTemplet eleTemplet,String basePath){
		String encoding = "UTF-8";

    	String templateId = eleTemplet.getId();
		String destPath = basePath + "/theme/conf/"+templateId+"/theme.xml";
		String filePath = basePath.replace("\\elevator\\","");

        EleSourceFont est = eleSourceFontService.get(eleTemplet.getFont());
        
        String fontFile = filePath + est.getFont();
        System.out.println(destPath);
        String fontName = est.getFont();
        if(fontName != null){
            fontName = fontName.substring(fontName.lastIndexOf("/") + 1, fontName.length());
            eleTemplet.setFont(new EleSourceFont("", "font/"+fontName));
        }

		String eleTempletXML = eleTempletPublishService.eleTempletToXml(eleTemplet);
		File theme = new File(destPath);
		File font = new File(fontFile);
		System.out.println(fontFile);
		try {
			FileUtils.writeStringToFile(theme, eleTempletXML, encoding,false);
			Map<String,List<File>> map = new HashMap<String,List<File>>();
			List<File> themes = new ArrayList<File>();
			themes.add(theme);		
			map.put("theme", themes);
			List<File> fonts = new ArrayList<File>();
			fonts.add(font);
			map.put("font", fonts);
			String zipPath = basePath + "/theme/source/"+templateId+"/";
			String zipName = templateId + ".zip";
			zipFiles(zipPath, zipName, map);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }
    public boolean zipFiles(String zipPath, String zipName, Map<String,List<File>> map) {

		// String tmpFileName = "report.zip";
		byte[] buffer = new byte[1024];
		// String strZipPath =
		// COM_REPORT_PATH+"/"+user.getOid()+"/"+report.getOid()+"/"+tmpFileName;

		String strZipPath = zipPath + "/" + zipName;
		try {
			File tmpZip = new File(zipPath);
			if (!tmpZip.exists())
				tmpZip.mkdirs();
			File tmpZipFile = new File(strZipPath);
			if (!tmpZipFile.exists())
				tmpZipFile.createNewFile();

			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
			Set<String> keys = map.keySet();
			for(String key:keys){
				List<File> files = map.get(key);
				String dir = key+"/";
				if(key.equals("theme")){
					dir = "/";
				}

				System.out.println(key);
				//增加外部文件夹
				out.putNextEntry(new ZipEntry(dir));  
				for (int i = 0; i < files.size(); i++) {
					FileInputStream fis = new FileInputStream(files.get(i));
					out.putNextEntry(new ZipEntry(dir+files.get(i).getName()));
					// 设置压缩文件内的字符编码，不然会变成乱码
					out.setEncoding("UTF-8");
					int len;
					// 读入需要下载的文件的内容，打包到zip文件
					while ((len = fis.read(buffer)) > 0) {
						out.write(buffer, 0, len);
					}
					out.closeEntry();
					fis.close();
				}
				out.closeEntry();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping("selectSource")
	public String selectSource(EleTemplet eleTemplet, Model model) {
        eleTempletService.save(eleTemplet,null);

        // 生成代码
        if("0".equals(eleTemplet.getFlag())){
            return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/designTemplet?id="+eleTemplet.getId();
        }
        else{
            return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/?repage";
        }
	}

    @RequiresPermissions("templet:eleTemplet:edit")
    @RequestMapping("designTemplet")
    public String designTemplet(EleTemplet eleTemplet, Model model) {
        model.addAttribute("eleTemplet", eleTemplet);
        return "modules/templet/designTempletForm";
    }

    @RequiresPermissions("templet:eleTemplet:edit")
    @RequestMapping("saveTempeteSource")
    @ResponseBody
    public Result saveTempeteSource(String eleTempletId,
                                    String name,
                                    String type,
                                    int width,
                                    int height,
                                    String remarks,
                                    String displaymode,
                                    String font,
                                    String fullscreen,
                                    String color,
                                    String bgImage,
                                    String bgGif,

                                    String eleTempletSourceList,
                                    HttpServletRequest request){
        logger.info(eleTempletSourceList);
        eleTempletSourceList = eleTempletSourceList.replace("&quot;","\"");

        EleTemplet entity = new EleTemplet(eleTempletId);
        entity.setName(name);
        entity.setType(new EleEquipmentType(type));
        entity.setWidth(width);
        entity.setHeight(height);
        entity.setRemarks(remarks);
        entity.setDisplaymode(displaymode);
        entity.setFont(new EleSourceFont(font));
        entity.setFullscreen(fullscreen);
        EleSourceBackground back = new EleSourceBackground();
        back.setColor(color);
        back.setBgImage(bgImage);
        back.setBgGif(bgGif);
        entity.setBackground(back);
        User user = UserUtils.getUser();
        entity.setCheckBy(user);
        entity.setCheckDate(new Date());
        entity.setDelFlag("0");
        List<EleTempletSource> templetSourceList = new ArrayList<>();
        Map map = JsonMapper.getInstance().fromJson(eleTempletSourceList, Map.class);
        for(Object item : map.keySet()){
            Map mapItem= (Map)map.get(item);

            EleTempletSource templetSource = JSONObject.parseObject(JSONObject.toJSONString(mapItem), EleTempletSource.class);

            int itemWidth = parseInt(templetSource.getWidth());
            int itemHeight = parseInt(templetSource.getHeight());
            int itemXloc = parseInt(templetSource.getXloc());
            int itemYloc = parseInt(templetSource.getYloc());

            if(itemWidth < 0){
                itemWidth = 0;
            }
            if(itemHeight < 0){
                itemHeight = 0;
            }
            if(itemXloc < 0){
                itemXloc = 0;
            }
            if(itemYloc < 0){
                itemYloc = 0;
            }

            templetSource.setWidth(String.valueOf(itemWidth));
            templetSource.setHeight(String.valueOf(itemHeight));
            templetSource.setXloc(String.valueOf(itemXloc));
            templetSource.setYloc(String.valueOf(itemYloc));
            templetSourceList.add(templetSource);
        }
        entity.setEleTempletSourceList(templetSourceList);

        eleTempletService.save(entity, "position");
	    String basePath = Global.getUserfilesBaseDir();
        String msg  ="";
        try{
            createTemplateFile(entity, basePath);
        }
        catch(Exception e){
            logger.error(e.getMessage());
            msg = "生成主题包失败!";
        }
        return new Result(Result.SUCCESS, msg, entity.getId());
    }

    private int parseInt(String value){
        value = StringUtils.defaultIfEmpty(value, "0").replace("px", "");
        if(isNum(value)){
            return Integer.parseInt(value);
        }
        return 0;
    }
    private boolean isNum(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    @RequiresPermissions("templet:eleTemplet:view")
    @RequestMapping(value = "show")
    public String show(EleTemplet eleTemplet) {
        return "modules/templet/eleTempletShow";
    }

    @RequiresPermissions("templet:eleTemplet:view")
    @RequestMapping(value = "info")
    public String info(String publishId, Model model){
        if(StringUtils.isNotEmpty(publishId)){
            EleTempletPublish publish = eleTempletPublishService.get(publishId);
            model.addAttribute("publish", publish);
            EleTemplet eleTemplet = eleTempletService.get(publish.getTemplet().getId());
            model.addAttribute("eleTemplet", eleTemplet);
        }

        return "modules/templet/eleTempletInfo";
    }

    @RequiresPermissions("templet:eleTemplet:view")
    @RequestMapping(value = "complete")
    public String complete(EleTemplet eleTemplet) {
        return "modules/templet/eleTempletComplete";
    }


    @RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "delete")
	public String delete(EleTemplet eleTemplet, RedirectAttributes redirectAttributes) {
		eleTempletService.delete(eleTemplet);
		addMessage(redirectAttributes, "删除模板成功");
		return "redirect:"+Global.getAdminPath()+"/templet/eleTemplet/?repage";
	}
    @RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "copy")
	public String copy(EleTemplet eleTemplet, RedirectAttributes redirectAttributes,Model model) {
    	List<EleTempletSource> sourceList = eleTemplet.getEleTempletSourceList();
    	eleTemplet.setId("");
    	eleTemplet.setName("");
		for(EleTempletSource source:sourceList) {
			source.setId("");
		}
		eleTemplet.setEleTempletSourceList(sourceList);
		//eleTempletService.save(eleTemplet,"copy");
		//System.out.println("===================================="+eleTemplet.getId());
		model.addAttribute("eleTemplet", eleTemplet);
        model.addAttribute("eleTempletSource", new EleTempletSource());
		return "modules/templet/eleTempletForm";
	}

    @RequiresPermissions("templet:eleTemplet:publish")
    @RequestMapping(value = "applypublish")
    public String applypublish(EleTemplet eleTemplet, EleEquipment eleEquipment, Model model){
    	 List<Office> listTree = new ArrayList<>();

	        User current = UserUtils.getUser();
	       
			List<User> resultList = getBranchForUser(current);
			Set<String> ids = new HashSet<String>();
			for(User temuser:resultList){
				 String officeId = temuser.getOffice().getId();
				 String companyId = temuser.getCompany().getId();
				ids.add(officeId);
				ids.add(companyId);
			}
			List<Office> listOffice = officeService.findList(true);
			
		
			Set<String> officeIds = new HashSet<>();
			Set<String> eqIds = new HashSet<>();
			for(User tmp:resultList){
				EleEquipment eleEquipmentTmp = new EleEquipment();
				eleEquipmentTmp.setCompany(tmp.getCompany());
				eleEquipmentTmp.setOffice(tmp.getOffice());

				List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
				for (EleEquipment equipment : listEquipment) {
					officeIds.add(equipment.getCompany().getId());
					officeIds.add(equipment.getOffice().getId());
					if(eqIds.contains(equipment.getId())){
						continue;
					}
					eqIds.add(equipment.getId());
					Office Office = new Office();
					Office.setId(equipment.getId());
					Office.setParent(new Office(equipment.getOffice().getId()));
					Office.setAddress(equipment.getCode());
					Office.setEmail(equipment.getType().getName());
					Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
					Office.setRemarks(equipment.getRemarks());
					if("1".equals(equipment.getState())){
						Office.setGrade("在线");
					}else{
						Office.setGrade("离线");
					}
					Office.setPhone("");
					listTree.add(Office);
				}
			}
			Set<String> resultSet = new HashSet<String>();
			for (String oid : officeIds) {
				resultSet.add(oid);
				Office tmp = officeService.get(oid);
				for (int i = 0; i < listOffice.size(); i++) {
					Office item = listOffice.get(i);
					if (item.getId().equals(tmp.getParentId())) {
						System.out.println(item);
						tmp = item;
						i = -1;
						resultSet.add(item.getId());
					}
				}
			}
			for(String oid:resultSet){
				Office item = officeService.get(oid);
				item.setAddress(null);
				item.setEmail(null);
				item.setFax(null);
				item.setRemarks(null);
				item.setGrade(null);
				item.setPhone("display:none;");
				listTree.add(item);
			}
		model.addAttribute("list", listTree);
		model.addAttribute("user", current);
		model.addAttribute("eleEquipment", eleEquipment);
        model.addAttribute("eleTemplet", eleTemplet);

        return "modules/templet/eleTempletPublish";
    }
    private List<User> getBranchForUser(User current){	
		User user = new User();
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (role.getEnname().equals("admin")) {
			resultList = list;
		} else if (role.getEnname().equals("user")) {
			resultList.add(current);
		} else if (role.getEnname().equals("operate")) {
			for (User usr : list) {
				if (usr.getRole().getEnname().equals("user")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getRole().getEnname().equals("operate")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getRole().getEnname().equals("user") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		}
		return resultList;
}
    @RequiresPermissions("templet:eleTemplet:publish")
    @RequestMapping(value = "publish")
    @ResponseBody
    public Result publish(String equipmentLists, String egId){
        User thisuser = UserUtils.getUser();
        String[] ems = equipmentLists.split(",");
        boolean noNeedCheck = UserUtils.getSubject().isPermitted("templet:eleTemplet:check") || SwitchUtils.isClose("templet:eleTemplet:check");
        System.out.println(egId);
        // 设置 申请 批次
        String publishBatch = IdGen.uuid();
        List<EleTempletPublish> publishList = new ArrayList<>();
        for(String emId : ems){
            if(StringUtils.isNotBlank(emId)){
                EleTempletPublish esgp = new EleTempletPublish();
                esgp.setPublishBatch(publishBatch);
                esgp.setEquipment(new EleEquipment(emId));
                esgp.setTemplet(new EleTemplet(egId));
               

                if (noNeedCheck){
                    esgp.setCheckDate(new Date(System.currentTimeMillis()));
                    esgp.setCheckBy(thisuser);
                    esgp.setDelFlag(EleSourceGroupPublish.DEL_FLAG_NORMAL);
                }else{
                    esgp.setCheckBy(UserUtils.getCheckUser(""));
                    esgp.setDelFlag(EleSourceGroupPublish.DEL_FLAG_AUDIT);
                }
                publishList.add(esgp);
            }
        }
        eleTempletPublishService.batchInsertTemplet(publishList);

        return new Result(Result.SUCCESS, noNeedCheck ? "发布成功!" : "提交发布申请,等待管理员审核!", null);
    }

    @RequiresPermissions("templet:eleTemplet:edit")
    @RequestMapping("applylist")
    public String applylist(EleTempletPublish eleTemplet, HttpServletRequest request, HttpServletResponse response, Model model){
        User thisUser = UserUtils.getUser();
		eleTemplet.setCreateBy(thisUser);
        Page<EleTempletPublish> page = eleTempletPublishService.findPublishPage(new Page<EleTempletPublish>(request, response), eleTemplet);
        model.addAttribute("page", page);
        return "modules/templet/myEleTempletList";
    }

	/**
	 * 审核记录
	 * @param eleTemplet
	 * @param isFirst
	 * @param flag
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
    @RequiresPermissions("templet:eleTemplet:check")
    @RequestMapping("mychecklist")
    public String checklist(EleTempletPublish eleTemplet,String isFirst, boolean flag, HttpServletRequest request, HttpServletResponse response, Model model){
        User thisUser = UserUtils.getUser();

        if(StringUtils.isEmpty(isFirst)){
        	eleTemplet.setDelFlag(User.DEL_FLAG_AUDIT);
		}
		List<User> branches = this.getSubListForUserForCheck(thisUser);
		Page<EleTempletPublish> page = new Page<>();
		if(!branches.isEmpty()){
			page = eleTempletPublishService.findPublishPageForCheck(new Page<EleTempletPublish>(request, response), branches, eleTemplet.getDelFlag());
		}
        model.addAttribute("page", page);
        model.addAttribute("flag", flag);
		model.addAttribute("isFirst", "no");

        return "modules/templet/myEleTempletCheckList";
    }
    @RequiresPermissions("templet:eleTemplet:check")
    @RequestMapping(value = "check")
    public String check(String publishId, String delFlag, RedirectAttributes redirectAttributes){
	    EleTempletPublish publish = new EleTempletPublish(publishId);
	    Result result;
	    if("1".equals(delFlag)){
		    result = eleTempletPublishService.delApprovalPublish(publish);
	    }
	    else{
		    publish.setDelFlag(delFlag);

		    publish.setCheckDate(new Date());
		    publish.setCheckBy(UserUtils.getUser());
		    result = eleTempletPublishService.checkPublish(publish);
	    }
	    addMessage(redirectAttributes, result.getMsg());
	    return "redirect:" + adminPath + "/templet/eleTemplet/info?publishId=" + publishId;
    }
    @RequiresPermissions("templet:eleTemplet:view")
    @RequestMapping("resubmit")
    @ResponseBody
    public Result resubmitTemplete(String templetList){
    	  String templets = templetList.substring(0, templetList.length()-1);

          System.out.println(templets);

          String status = EleTempletPublish.DEL_FLAG_AUDIT;
  		  String msg = "已重新提交审核";
          User thisuser = UserUtils.getUser();
          eleTempletPublishService.bathcUpdateTempletStatus(templets, status, thisuser.getId());

          return new Result(Result.SUCCESS, msg, null);
    }

    @RequiresPermissions("equipment:eleEquipment:check")
    @RequestMapping("checkList")
    @ResponseBody
    public Result checkList(String templetList, String flag, String type){
        String templets = templetList.substring(0, templetList.length()-1);

        System.out.println(templets);

        String status;
        String msg;
        if("delete".equals(flag)){
            status = EleEquipment.DEL_FLAG_DELETE;
            msg = "删除成功";
	        if("approval".equals(type)){
		        eleTempletPublishService.delApprovalTempletStatus(templets, status);
	        }
	        else{
		        eleTempletPublishService.delApplyTempletStatus(templets, status);
	        }

	        return new Result(Result.SUCCESS, msg, null);
        }

	    User thisuser = UserUtils.getUser();
        if("reject".equals(flag)){
            status = EleEquipment.DEL_FLAG_AUDIT_NO;
            msg = "未通过审核";
        }
        else{
            status = EleEquipment.DEL_FLAG_NORMAL;
            msg = "审核通过";
        }
        eleTempletPublishService.bathcUpdateTempletStatus(templets, status, thisuser.getId());
        return new Result(Result.SUCCESS, msg, null);
    }

    @RequiresPermissions("equipment:eleEquipment:edit")
    @RequestMapping(value = "download")
    public void download(EleTemplet eleTemplet, HttpServletResponse response){
	    String basePath = Global.getUserfilesBaseDir();
       String zipPath = basePath + "/theme/source/"+eleTemplet.getId()+"/";
       String zipName = eleTemplet.getId() + ".zip";
       downloadFile(zipPath, zipName, response);
    }
    public void downloadFile(String filePath, String fileName, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		// response.setContentType("application/octet-stream");

		try {
			File file = new File(filePath, fileName);
			// 以流的形式下载文件。
			BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			toClient.write(buffer);
			toClient.flush();
			toClient.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
    @RequiresUser
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> list(EleTemplet eleTemplet, HttpServletResponse response) {
        response.setContentType("application/json; charset=UTF-8");
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<EleTemplet> list = eleTempletService.findList(eleTemplet);
        for(EleTemplet e : list){
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", 0);
            map.put("name", e.getName());
            mapList.add(map);
        }
        return mapList;
    }
    public List<User> getSubListForUserForCheck(User current){
		User user = new User();
		user.setDelFlag(null);
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (role.getEnname().equals("admin")) {
			for (User usr : list) {
					resultList.add(usr);
			}
		} else if (role.getEnname().equals("user")) {
			//resultList.add(current);
		} else if (role.getEnname().equals("operate")) {
			for (User usr : list) {
				if (usr.getRole().getEnname().equals("user")
						&& usr.getCompany().getId().equals(current.getCompany().getId()) && usr.getOffice().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			//resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getRole().getEnname().equals("operate")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getRole().getEnname().equals("user") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			//resultList.add(current);
		}
		for (User temuser : resultList) {
			temuser.setRemarks(User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag()) ? "正常" : "审核中");
		}
		return resultList;
	}
}